package com.hyyt.shopjsp.basic.controller;

import com.hyyt.shopjsp.basic.pojo.BasicFunctions;
import com.hyyt.shopjsp.basic.pojo.BasicPurview;
import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicFunctionsService;
import com.hyyt.shopjsp.basic.service.IBasicPurviewService;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import com.hyyt.shopjsp.util.tree.NodeUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Copyright (c) 2016 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Zhang Dingfang on 2016/10/24 0024上午 11:10.
 */
@Controller
@RequestMapping("/back/purview/")
public class BasicPurviewController extends BaseController {

    private Logger logger = Logger.getLogger(BasicPurviewController.class);
    private String basePath = "/back/basic/purview/";

    @Resource
    private IBasicPurviewService basicPurviewService;
    @Resource
    private IBasicFunctionsService basicFunctionsService;

    /**
     * 进入权限管理列表
     * @return 进入指定页面
     */
    @RequestMapping("gotoPurviewPage")
    public String gotoPurviewPage() {
        return basePath + "purviewList";
    }

    /**
     * 获得权限的单个对象
     * @param purviewId
     * @return
     */
    @RequestMapping(value = "getPurviewObject", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg getPurviewObject(Integer purviewId) {
        ResultMsg result = new ResultMsg(false);
        if (Utils.objectIsNotEmpty(purviewId)) {
            BasicPurview purview = basicPurviewService.loadBasicPurview(purviewId);
            return new ResultMsg(true, null, FastJsonUtils.toJSONString(purview));
        }
        return result;
    }


    /**
     * 得到权限对象列表
     * @param purviewId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getResetPurviewList", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg getResetPurviewList(Integer purviewId) throws Exception {
        List<BasicPurview> purviewList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();
        param.put("levelCode", 1);
        param.put("parentId", 1);
        param.put("sortColumns", "sortCode asc");
        List<BasicPurview> pList1 = basicPurviewService.queryBasicPurview(param); // .findObjects(" where  (levelCode=1 or purviewId=1) and purviewId!="+purviewId+"  order by ");
        if(Utils.objectIsNotEmpty(pList1)){
            for(BasicPurview p1:pList1){
                purviewList.add(p1);
                if(p1.getPurviewId()!=1){
                    param.clear();
                    param.put("parentId", p1.getPurviewId());
                    param.put("purviewId", purviewId);
                    param.put("sortColumns", "sortCode asc");
                    List <BasicPurview> pList2 = basicPurviewService.queryBasicPurview(param);
                    if(Utils.objectIsNotEmpty(pList2)){
                        for(BasicPurview p2:pList2){
                            purviewList.add(p2);
                        }
                    }
                }
            }
        }
        return new ResultMsg(true, null, FastJsonUtils.toJSONString(purviewList));
    }

    /**
     * 获得权限树节点
     * @return
     */
    @ResponseBody
    @RequestMapping("getNodes")
    public void getNodes(HttpServletResponse response){
        Map<String, Object> param = new HashMap<>();
        String [] selectColmunsArray={"purviewId","purviewName","parentId","isLeaf"};
        param.put("selectColmunsArray",selectColmunsArray);
        param.put("sortColumns", "sortCode asc");
        List<BasicPurview> purviewList=basicPurviewService.queryAllBasicPurviewByMap(param);
        List nodeList = new ArrayList();
        HashMap nodeMap = new HashMap();
        for(int i = 0; i < purviewList.size(); i++) {
            BasicPurview bp = purviewList.get(i);
            nodeMap = new HashMap();
            nodeMap.put("id",bp.getPurviewId());
            nodeMap.put("text", bp.getPurviewName());
            nodeMap.put("isLeaf", bp.getIsLeaf());
            String parentId = String.valueOf(bp.getParentId());
            if (Utils.objectIsEmpty(parentId)) {
                parentId = "0";
            }
            nodeMap.put("parentId",parentId);
            nodeList.add(nodeMap);
        }
        //获取分类的json字符串信息
        String jsonInfo= NodeUtil.getNodeJson(nodeList,"系统权限");
        ResultMsg.create(jsonInfo, response, false);
    }

    /**
     * 查询指定权限下的子权限列表
     *
     * @param page
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "listSubPurviewByParentId", method = RequestMethod.POST)
    @ResponseBody
    public void listSubPurviewByParentId(Integer parentId, String purviewName, Page page, HttpServletResponse response) {
        Map<String, Object> param = new HashMap<>();
        if (Utils.objectIsEmpty(parentId)) {
            parentId=0;
        }
        param.put("parentId",parentId.toString());
        if (Utils.objectIsNotEmpty(purviewName)) {
            param.put("purviewName", purviewName);
        }
        int totalRecordCount = basicPurviewService.countBasicPurview(param);
        //定义查询的字段
        String [] selectColmunsArray={"purviewId","purviewName","parentId","sortCode","isLeaf"};
        param.put("selectColmunsArray",selectColmunsArray);
        param.put("sortColumns", "sortCode asc");
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<BasicPurview> list = basicPurviewService.queryBasicPurview(param, page.getPageRecordBeginIndex(), page.getPageSize());
        param.clear();
        param.put("total", totalRecordCount);// total键 存放总记录数，必须的
        param.put("rows", list);// rows键 存放每页记录 list
        param.put("parentId", parentId);
        //param.put("currentLevelCode", currentLevelCode);
        ResultMsg.create(param, response);  //把内容发送到页面
    }

    /**
     * 查询指定权限下的子权限列表,用于角色分配权限功能
     *
     * @param page
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "listIsLeafPurviewByParentId", method = RequestMethod.POST)
    @ResponseBody
    public void listIsLeafPurviewByParentId(Integer actorId,Integer parentId, String purviewName, Page page, HttpServletResponse response) {
        Map<String, Object> param = new HashMap<>();
        if (Utils.objectIsNotEmpty(parentId)) {
            param.put("parentId", String.valueOf(parentId));
        }else{//默认展开系统信息下所有的三级权限菜单
            param.put("parentId","2");
        }

        if (Utils.objectIsNotEmpty(actorId)) {//对应的角色id
            param.put("actorId", actorId);
        }

        if (Utils.objectIsNotEmpty(purviewName)) {
            param.put("purviewName", purviewName);
        }

        int totalRecordCount = basicPurviewService.countIsLeafBasicPurview(param);
        //定义查询的字段
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<Map<String,Object>> list = basicPurviewService.queryIsLeafBasicPurview(param, page.getPageRecordBeginIndex(), page.getPageSize());
        param.clear();
        param.put("total", totalRecordCount);// total键 存放总记录数，必须的
        param.put("rows", list);// rows键 存放每页记录 list
        param.put("parentId", parentId);
        ResultMsg.create(param, response);  //把内容发送到页面
    }

    /**
     * 保存或者修改权限
     * @param purview
     * @return
     */
    @RequestMapping(value = "saveOrUpdatePurview", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveOrUpdatePurview(BasicPurview purview) {
        BasicUsers basicUsers = getSessionUsers();
        ResultMsg result = new ResultMsg(false);
        result = basicPurviewService.saveBasicPurview(purview, basicUsers);
        return result;
    }

    /**
     * 删除指定权限
     * @param purviewId 权限Id
     * @return
     */
    @RequestMapping(value = "deletePurview", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deletePurview(Integer purviewId) {
        BasicUsers basicUsers = getSessionUsers();
        return basicPurviewService.deleteBasicPurview(basicUsers, purviewId);
    }

    /**
     * 查询所有信息列表
     */
    @RequestMapping(value = "listFunctions", method = RequestMethod.POST)
    @ResponseBody
    public void listFunctions(String funName,Integer purviewId, Page page, HttpServletResponse response) {
        Map<String, Object> param = new HashMap<>();
        if (funName!=null&&!"".equals(funName.trim())) {
            param.put("funName", funName);
        }
        param.put("purviewId", purviewId);
        int totalRecordCount = basicFunctionsService.countBasicFunctions(param);
        param.put("sortColumns", "fid asc");
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<Map<String,Object>> functionsList = basicFunctionsService.queryBasicFunctions(param, page.getPageRecordBeginIndex(), page.getPageSize());
        param.clear();
        param.put("total", totalRecordCount);// total键 存放总记录数，必须的
        param.put("rows", functionsList);// rows键 存放每页记录 list
        ResultMsg.create(param, response);  //把内容发送到页面*/
    }

    /**
     * 获取一条记录
     */
    @RequestMapping(value = "getFunctionsObject", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg getFunctionsObject(Integer fid) {
        if (Utils.objectIsNotEmpty(fid)){
            BasicFunctions functions = basicFunctionsService.loadBasicFunctions(fid);
            return ResultMsg.create(true, null, FastJsonUtils.toJSONString(functions));
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 保存或者修改
     * @param functions
     * @return
     */
    @RequestMapping(value = "saveOrUpdateFunctions", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveOrUpdateFunctions(BasicFunctions functions){
        boolean flag = false;
        if(Utils.objectIsNotEmpty(functions)){
            functions = basicFunctionsService.saveOrUpdateObject(functions);
            if(functions.getFid()!=null){
                flag = true;
            }
            return ResultMsg.create(flag);
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 删除
     * @param fid
     * @return
     */
    @RequestMapping(value = "deleteFunctions", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deleteFunctions(Integer fid){
        if(Utils.objectIsNotEmpty(fid)){
            basicFunctionsService.deleteBasicFunctions(fid);
            return ResultMsg.create(true);
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 检查权限校验编码是否已经存在
     *
     * @param purviewValidateCode 权限校验编码
     * @param purviewId  权限id
     * @return
     */
    @RequestMapping(value = "checkPurviewValidateCode", method = RequestMethod.POST)
    @ResponseBody
    public Map checkPurviewValidateCode(String purviewValidateCode, Integer purviewId) {
        Map<String, Object> param = new HashMap<>();
        boolean flag=false;
        if (Utils.objectIsNotEmpty(purviewValidateCode)) {
            //统计名字的个数
            param.put("purviewValidateCode", purviewValidateCode);
            int countPurviewValidateCode = basicPurviewService.countBasicPurview(param);

            if (countPurviewValidateCode > 0) {
                if (Utils.objectIsNotEmpty(purviewId)) {
                    //统计名字是否为当前用户的
                    param.put("purviewId", purviewId);
                    int countPurviewId = basicPurviewService.countBasicPurview(param);
                    if (countPurviewId == 1) {
                        flag=true;
                    }
                }
            } else {
                flag=true;
            }
        }
        param.clear();
        param.put("valid",flag);//bootstrap validator 远程校验需要返回{"valid",true}
        return param;
    }

}